package meijuli.com.join51.business.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.jhx.common.utils.Constants;
import meijuli.com.join51.business.R;
import meijuli.com.join51.business.SimpleTextWatch;
import meijuli.com.join51.business.model.SmsCode;
import meijuli.com.join51.business.service.ApiService;
import meijuli.com.join51.business.setpaypwd.PayPwdActivity;
import com.jhx.common.http.ApiManager;
import com.jhx.common.http.HttpRequest;
import com.jhx.common.http.HttpResponse;
import com.jhx.common.http.ResponseCallback;
import com.jhx.common.model.User;
import com.jhx.common.utils.MD5Utils;
import meijuli.com.join51.business.utils.StringUtil;
import com.jhx.common.utils.ToastUtil;
import com.jhx.common.utils.UserManager;
import retrofit2.Call;

import static android.text.Spanned.SPAN_INCLUSIVE_INCLUSIVE;

/**
 * 设置支付密码
 *
 * @author wenqin 2017-05-06 15:00
 */

public class SetPayPwdFragment extends BaseFragment {
    Button mGetAuthCodeBtn;
    EditText mVerifyCodeView;
    TextView mPhoneText;
    Button mStepBtn;
    private String mCode;
    private boolean isGetCode = false;
    private Call<HttpResponse<SmsCode>> mCall;
    private int mPwdIsExist = PayPwdActivity.SET_PASSWORD;
    private CountDownTimer mDownTimer;
    private String mPhone;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_set_pay_pwd, container, false);
        mGetAuthCodeBtn = view.findViewById(R.id.get_auth_code_btn);
        mVerifyCodeView = view.findViewById(R.id.verify_code_view);
        mPhoneText = view.findViewById(R.id.text_phone);
        mStepBtn = view.findViewById(R.id.btn_step);
        return view;
    }

    public static SetPayPwdFragment newInstance(int type) {
        SetPayPwdFragment fragment = new SetPayPwdFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(PayPwdActivity.KEY_TYPE, type);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mPwdIsExist = getArguments().getInt(PayPwdActivity.KEY_TYPE);
        mStepBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!isGetCode) {
                    ToastUtil.getInstance().showToast(getActivity(), "请先获取验证码~");
                    return;
                } else if(!StringUtil.isValidateVerifyCode(mVerifyCodeView.getText().toString())) {
                    ToastUtil.getInstance().showToast(getActivity(), "验证码输入有误~");
                    return;
                } else if(!mCode.equals(MD5Utils.getMD5(mVerifyCodeView.getText().toString()))) {
                    ToastUtil.getInstance().showToast(getActivity(), "验证码不正确，请重新输入~");
                    return;
                }
                Intent intent = new Intent(getActivity(), PayPwdActivity.class);
                intent.putExtra(PayPwdActivity.KEY_TYPE, mPwdIsExist);
                intent.putExtra(PayPwdActivity.KEY_CODE, mVerifyCodeView.getText().toString().trim());
                intent.putExtra(PayPwdActivity.KEY_PHONE, mPhone);
                startActivity(intent);
            }
        });
        mGetAuthCodeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isGetCode = true;
                showLoadingDialog();

                mCall = ApiManager.get().getApiService(ApiService.class).getSmsCode(mPhone, Constants.CodeType.mPayPwdCode);
                HttpRequest.getRequest().autoRecycle(SetPayPwdFragment.this).start(mCall, new ResponseCallback<SmsCode>() {

                    @Override
                    public void onSuccess(String url, SmsCode data) {
                        dismissDialog();
                        doTimer();
                        if(data != null && !TextUtils.isEmpty(data.getVerifyCode())) {
                            mCode = data.getVerifyCode();
                        }
                    }

                    @Override
                    public void onError(String url, int errorCode, String errorMsg) {
                        super.onError(url, errorCode, errorMsg);
                        dismissDialog();
                    }
                });
            }
        });
        mVerifyCodeView.addTextChangedListener(new SimpleTextWatch() {
            @Override
            public void afterTextChanged(Editable editable) {
                if (TextUtils.isEmpty(mVerifyCodeView.getText().toString())) {
                    mStepBtn.setEnabled(false);
                } else {
                    mStepBtn.setEnabled(true);
                }
            }
        });

        User user = UserManager.get().getUser();
        if (UserManager.get().checkUserNull(mActivity)) {
            return;
        }

        mPhone = user.getPhone();
        mPhoneText.setText(String.format("我们将发送验证码到您的手机\n%s", mPhone));
        SpannableString ss = new SpannableString(mPhoneText.getText());
        ss.setSpan(new ForegroundColorSpan(Color.parseColor("#F39F00")), 5, 8, SPAN_INCLUSIVE_INCLUSIVE);
        mPhoneText.setText(ss);
    }

    public void doTimer() {
        mDownTimer = new CountDownTimer(120 * 1000, 1000) {
            @SuppressLint("DefaultLocale")
            @Override
            public void onTick(long time) {
                mGetAuthCodeBtn.setEnabled(false);
                mGetAuthCodeBtn.setText(String.format("%ds", time / 1000));
            }

            @Override
            public void onFinish() {
                mGetAuthCodeBtn.setEnabled(true);
                mGetAuthCodeBtn.setText("重新获取");
            }
        };
        mDownTimer.start();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mDownTimer != null) {
            mDownTimer.cancel();
        }
    }
}
